package kr.hkit.androidcomplete03.ch25;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SQLiteTest extends Activity {
	WordDbHelper mHelper;
	ListView list;
	WordDAO dao;
	SimpleCursorAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sqlitetest);
		mHelper = new WordDbHelper(this);
		list = (ListView) findViewById(R.id.list);
		dao = WordDAO.open(this);
	}
	
	public void mOnClick(View v){
		boolean result;
		String str = null;
		switch(v.getId()){
		case R.id.insertBtn:
			EditText eng = (EditText) findViewById(R.id.engEdit);
			EditText han = (EditText) findViewById(R.id.hanEdit);
			result = dao.insert(eng.getText().toString(), han.getText().toString());
			str = result?"Insert Success":"Insert Fail";
			eng.setText("");
			han.setText("");
			break;
		case R.id.deleteAllBtn:
			result = dao.deleteAll();
			str = result?"DeleteAll Success":"DeleteAll Failed";
			break;
		case R.id.deleteBtn:
			EditText num = (EditText) findViewById(R.id.idEdit);
			int idx = Integer.parseInt(num.getText().toString());
			result = dao.delete(idx);
			str = result?"Delete Success":"Delete Failed";
			break;
		case R.id.updatebtn:
			EditText updateNum = (EditText) findViewById(R.id.updatenum);
			EditText updateEng = (EditText) findViewById(R.id.updateeng);
			EditText updateHan = (EditText) findViewById(R.id.updatehan);
			int id = Integer.parseInt(updateNum.getText().toString());
			 
			result = dao.update(id, updateEng.getText().toString(), updateHan.getText().toString());
			str = result?"Update Success":"Update Failed";
			updateNum.setText("");
			updateEng.setText("");
			updateHan.setText("");
			break;
		case R.id.selectBtn:
			Cursor cursor = dao.selectAll();
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(
					this, 
					R.layout.listrow, 
					cursor, 
					new String[]{"_id", "eng", "han"}, 
					new int[]{R.id.listnum, R.id.listeng, R.id.listhan}
					,SimpleCursorAdapter.NO_SELECTION);
			list.setAdapter(adapter);
			str="Select Success";
			break;
		}
		Toast.makeText(this, str, Toast.LENGTH_LONG).show();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		dao.close();
	}
}
